import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import queryString from 'query-string';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Card, Button, Row, Col, Spin, Select, message, InputNumber, Modal } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;

@connect(({ pricing, loading, publicdata }) => ({
  loading: loading.models.pricing,
  dictCode: publicdata.dictCode,
  detailInfo: pricing.detailInfo,
  productList: pricing.productList,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pdId: null,
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    const { pdId } = queryString.parse(location.search);
    if (pdId) {
      // 修改
      dispatch({
        type: 'pricing/getDetail',
        payload: {
          pdId,
        },
      });
    } else {
      // 新增
      dispatch({
        type: 'publicdata/fetchDictCode',
        payload: ['PD_CATE', 'PD_BILL_FREQ'],
      }).then(data => {
        if (data) {
          dispatch({
            type: 'pricing/getProductList',
          });
        }
      });
    }
    this.setState({ pdId });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const dataInfo = {
      detailInfo: {},
    };
    dispatch({
      type: 'pricing/updateModelData',
      payload: { ...dataInfo },
    });
    this.setState({ pdId: null });
  }

  // 选择产品
  selectProduct = (value, option) => {
    const { dispatch, dictCode } = this.props;
    dispatch({
      type: 'pricing/getProductInfo',
      payload: { detailInfo: option.props && option.props.datas, dictCode },
    });
  };

  // 提交数据
  submitData = () => {
    const { dispatch, form } = this.props;
    const { pdId } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'pricing/submit',
          payload: { values, pdId },
        }).then(response => {
          if (response.success) {
            message.success(pdId ? '保存成功!' : '新增成功！');
            if (!pdId) {
              confirm({
                title: '提交成功，是否继续添加特殊售价规则?',
                icon: <ExclamationCircleOutlined />,
                okText: '是',
                okType: 'default',
                cancelText: '否',
                style: { top: 200 },
                onOk: () => {
                  router.push(`/productmanage/pricing/speicf?pdId=${values.pdId}`);
                },
                onCancel: () => {
                  router.push('/productmanage/pricing/index');
                },
              });
            } else {
              router.push({
                pathname: '/productmanage/pricing/index',
              });
            }
          } else {
            message.warning(`${response.message || '保存失败！'}`);
          }
        });
      }
    });
  };

  render() {
    const { loading, form, productList, detailInfo } = this.props;
    const { getFieldDecorator } = form;
    const { pdId } = this.state;
    // 表单布局
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const formItemLayout = { xl, lg, md, sm };
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card title={`${pdId ? '修改' : '新增'}产品`}>
            <Form layout="inline" className={styles.productPrice}>
              <Row gutter={64}>
                <Col {...formItemLayout}>
                  {pdId ? (
                    <FormItem label="产品名称">{detailInfo.pdName || '--'}</FormItem>
                  ) : (
                    <FormItem label="选择产品">
                      {getFieldDecorator('pdId', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <HOCSelect
                          placeholder="请选择"
                          style={{ width: 200 }}
                          onChange={(value, option) => this.selectProduct(value, option)}
                          showSearch
                          optionFilterProp="children"
                        >
                          {productList.map(item => (
                            <Option key={item.pdId} datas={item}>
                              {item.pdName}
                            </Option>
                          ))}
                        </HOCSelect>
                      )}
                    </FormItem>
                  )}
                </Col>
                <Col {...formItemLayout}>
                  <FormItem label="默认建议售价">
                    {getFieldDecorator('suggPrice', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: detailInfo.suggPrice,
                    })(
                      <InputNumber
                        min={0}
                        max={9999999999.99}
                        placeholder="请输入"
                        style={{ width: '100%' }}
                        precision={2}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
              {detailInfo.pdId && (
                <Row gutter={64}>
                  <Col {...formItemLayout}>
                    <FormItem label="产品编号">{detailInfo.pdCode || '--'}</FormItem>
                  </Col>
                  <Col {...formItemLayout}>
                    <FormItem label="产品分类">{detailInfo.pdCateName || '--'}</FormItem>
                  </Col>
                  <Col {...formItemLayout}>
                    <FormItem label="收费频率">{detailInfo.billFreqName || '--'}</FormItem>
                  </Col>
                </Row>
              )}
              {detailInfo.pdId && <FormItem label="描述">{detailInfo.pdInfo || '--'}</FormItem>}
            </Form>
          </Card>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={() => router.goBack()}>取消</Button>
            <Button type="primary" onClick={this.submitData}>
              保存
            </Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
